package com.chen.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chen.bean.entity.UserEntity;
import com.chen.bean.enums.ResultCode;
import com.chen.bean.vo.WxLoginRequest;
import com.chen.bean.vo.WxUserInfo;
import com.chen.dao.UserMapper;
import com.chen.exception.BusinessException;
import com.chen.service.UserService;
import com.chen.util.JsonMapper;
import com.chen.util.JwtHelper;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserEntity queryById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public UserEntity queryByOpenId(String openId) {
        LambdaQueryWrapper<UserEntity> lqw = new LambdaQueryWrapper<UserEntity>();
        lqw.eq(UserEntity::getWeixinOpenid,openId);
        return userMapper.selectOne(lqw);
    }

    @Override
    public void insert(UserEntity entity) {
        userMapper.insert(entity);

    }

    @Override
    public void updateById(UserEntity entity) {
        userMapper.updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WxUserInfo loginByWx(WxLoginRequest request) throws BusinessException, WxErrorException {

        String sessionKey = null;
        String openId = null;
        try {
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(request.getCode());
            sessionKey = sessionInfo.getSessionKey();
            openId = sessionInfo.getOpenid();
        } catch (WxErrorException e) {
            log.error("get wxSessionInfo error==="+e.getMessage(),e);
            throw new WxErrorException(e.getMessage());
        }

        UserEntity userEntity = this.queryByOpenId(openId);
        if (ObjUtil.isNull(userEntity)){
            //插入
            userEntity = new UserEntity();
            userEntity.setUsername(openId);
            userEntity.setPassword(openId);
            userEntity.setWeixinOpenid(openId);
            userEntity.setAvatar(request.getAvatarUrl());
            userEntity.setNickname(request.getNickname());
            userEntity.setGender(request.getGender());
            userEntity.setSessionKey(sessionKey);
            userEntity.setCreateTime(new Date());
            userEntity.setUpdateTime(new Date());
            this.insert(userEntity);
        }else {
            //更新
            userEntity.setSessionKey(sessionKey);
            userEntity.setUpdateTime(new Date());
            userEntity.setNickname(request.getNickname());
            userEntity.setAvatar(request.getAvatarUrl());
            userEntity.setGender(request.getGender());
            this.updateById(userEntity);
        }

        //创建token
        String token = JwtHelper.createToken(JsonMapper.toJson(userEntity));
        if (StringUtils.isBlank(token)){
            throw new BusinessException(ResultCode.AUTHORIZED_ERROR.getCode(),ResultCode.AUTHORIZED_ERROR.getMessage());
        }
        WxUserInfo userInfo = new WxUserInfo();
        BeanUtil.copyProperties(request,userInfo);
        userInfo.setToken(token);
        //token刷新时间两小时
        userInfo.setExpiresIn((long) (2 * 60 * 60));
        userInfo.setUserId(userEntity.getId());
        return userInfo;
    }
}
